package com.crp.core.util;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;

public class JsonUtil {
    public static Map<String, Object> parseMap(String jsonStr) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            Map<String, ?> jsonMap = JSON.parseObject(jsonStr, Map.class);
            for (Map.Entry<String, ?> entry : jsonMap.entrySet()) {
                Object value = entry.getValue();
                String key = entry.getKey();
                if (value == null) {
                    resultMap.put(key, value);
                } else if (value instanceof String) {
                    resultMap.put(key, (String) value);
                } else if (value instanceof Integer) {
                    resultMap.put(key, (Integer) value);
                } else if (value instanceof Long) {
                    resultMap.put(key, (Long) value);
                } else if (value instanceof BigDecimal) {
                    resultMap.put(key, (BigDecimal) value);
                } else if (value instanceof String[]) {
                    resultMap.put(key, (String[]) value);
                } else if (value instanceof JSONArray) {
                    List listStr = (List) value;
                    if (listStr != null && listStr.size() > 0 && listStr.get(0) instanceof Map) {
                        List<Map> tList=JSON.parseArray(value.toString(), Map.class);
                        List<Map> list=new ArrayList<Map>();
                        for(Map tMap:tList){
                            Map<String, Object> subMap=parseMap(JSON.toJSONString(tMap));
                            list.add(subMap);
                        }
                    } else {
                        resultMap.put(key, value);
                    }
                }else{
                    Map<String, Object> subMap=parseMap(value.toString());
                    resultMap.put(key, subMap);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return resultMap;
    }
}
